package com.example.app.page;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import com.example.app.R;
import com.example.app.api.LoginService;
import com.example.app.config.RetrofitClient;
import com.example.app.entity.LoginRequest;
import com.example.app.entity.LoginResponse;
import com.example.app.entity.UserProfile;
import com.example.app.manager.TokenManager;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private EditText etUsername, etPassword;
    private Button btnLogin, btnRegister;
    private RetrofitClient retrofitClient;
    private TokenManager tokenManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        // 初始化组件
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        btnRegister = findViewById(R.id.btn_register);

        btnRegister.setOnClickListener(v -> {
            // 跳转到注册界面
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
            finish();
        });

        // 初始化Retrofit客户端
        retrofitClient = RetrofitClient.getInstance((Application) getApplicationContext());
        tokenManager = retrofitClient.getTokenManager();

        // 登录按钮点击事件（不需要Token）
        btnLogin.setOnClickListener(v -> performLogin());
    }

    // ==================== 不需要Token的请求 ====================
    private void performLogin() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        // 获取登录服务接口实例（不带Token）
        LoginService authService = retrofitClient.getLoginService(LoginService.class);
        Call<LoginResponse> call = authService.login(new LoginRequest(username, password));

        call.enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    // 保存Token到管理器
                    String token = response.body().getToken();
                    tokenManager.saveToken(token);
                    Log.e(TAG, "登录成功！Token: " + token);

                    fetchUserProfile();

                } else {
                    Log.e(TAG, "登录失败: HTTP " + response.code());
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                Log.e(TAG, "网络错误: " + t.getMessage());
            }
        });
    }

    // ==================== 需要Token的请求 ====================
    private void fetchUserProfile() {
        if (tokenManager.getToken() == null) {
            Log.e(TAG, "请先登录！");
            return;
        }

        // 获取用户服务接口实例（带Token）
        LoginService userService = retrofitClient.getAuthService(LoginService.class);
        Call<UserProfile> call = userService.getProfile();

        call.enqueue(new Callback<UserProfile>() {
            @Override
            public void onResponse(Call<UserProfile> call, Response<UserProfile> response) {
                if (response.isSuccessful() && response.body() != null) {
                    UserProfile profile = response.body();
                    tokenManager.saveUserProfile(profile);

                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }else {
                    Log.e(TAG, "请求失败: HTTP "+ response.code());
                }
            }

            @Override
            public void onFailure(Call<UserProfile> call, Throwable t) {
                Log.e(TAG, "网络错误: " +t.getMessage());
            }
        });
    }
}